// 网络请求工具类
const config = require('../config/config.js')

class Request {
  constructor() {
    this.baseUrl = config.baseUrl
    this.timeout = 10000
    this.header = {
      'Content-Type': 'application/json'
    }
  }

  // 设置请求头
  setHeader(key, value) {
    this.header[key] = value
  }

  // 设置Token
  setToken(token) {
    if (token) {
      this.setHeader('Authorization', `Bearer ${token}`)
    } else {
      delete this.header['Authorization']
    }
  }

  // 通用请求方法
  request(options) {
    return new Promise((resolve, reject) => {
      // 显示加载提示
      if (options.loading !== false) {
        wx.showLoading({
          title: options.loadingText || '加载中...',
          mask: true
        })
      }

      // 构建完整URL
      let url = options.url
      if (!url.startsWith('http')) {
        url = this.baseUrl + url
      }

      // 发起请求
      wx.request({
        url: url,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          ...this.header,
          ...options.header
        },
        timeout: options.timeout || this.timeout,
        success: (res) => {
          // 隐藏加载提示
          if (options.loading !== false) {
            wx.hideLoading()
          }

          // 处理响应
          this.handleResponse(res, resolve, reject, options)
        },
        fail: (err) => {
          // 隐藏加载提示
          if (options.loading !== false) {
            wx.hideLoading()
          }

          // 处理网络错误
          this.handleError(err, reject, options)
        }
      })
    })
  }

  // 处理响应
  handleResponse(res, resolve, reject, options) {
    const { statusCode, data } = res

    // HTTP状态码检查
    if (statusCode >= 200 && statusCode < 300) {
      // 业务逻辑检查
      if (data.success !== false) {
        resolve(data)
      } else {
        // 业务错误
        const error = {
          code: data.code || 'BUSINESS_ERROR',
          message: data.message || '操作失败',
          data: data.data
        }
        
        if (options.showError !== false) {
          this.showError(error.message)
        }
        
        reject(error)
      }
    } else if (statusCode === 401) {
      // 未授权，清除token并跳转登录
      this.handleUnauthorized()
      reject({
        code: 'UNAUTHORIZED',
        message: '请先登录',
        statusCode
      })
    } else if (statusCode === 403) {
      // 权限不足
      const error = {
        code: 'FORBIDDEN',
        message: '权限不足',
        statusCode
      }
      
      if (options.showError !== false) {
        this.showError(error.message)
      }
      
      reject(error)
    } else {
      // 其他HTTP错误
      const error = {
        code: 'HTTP_ERROR',
        message: data.message || `请求失败 (${statusCode})`,
        statusCode
      }
      
      if (options.showError !== false) {
        this.showError(error.message)
      }
      
      reject(error)
    }
  }

  // 处理网络错误
  handleError(err, reject, options) {
    console.error('网络请求失败:', err)
    
    const error = {
      code: 'NETWORK_ERROR',
      message: '网络连接失败，请检查网络设置',
      originalError: err
    }
    
    if (options.showError !== false) {
      this.showError(error.message)
    }
    
    reject(error)
  }

  // 处理未授权
  handleUnauthorized() {
    // 清除本地存储的用户信息
    wx.removeStorageSync(config.cacheKeys.token)
    wx.removeStorageSync(config.cacheKeys.userInfo)
    
    // 清除请求头中的token
    this.setToken(null)
    
    // 提示用户重新登录
    wx.showModal({
      title: '登录过期',
      content: '登录已过期，请重新登录',
      showCancel: false,
      success: () => {
        // 跳转到登录页面或个人中心
        wx.switchTab({
          url: '/pages/profile/profile'
        })
      }
    })
  }

  // 显示错误信息
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    })
  }

  // GET请求
  get(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'GET',
      data,
      ...options
    })
  }

  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  // PUT请求
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  // DELETE请求
  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  }

  // 文件上传
  uploadFile(options) {
    return new Promise((resolve, reject) => {
      // 显示上传进度
      if (options.showProgress !== false) {
        wx.showLoading({
          title: '上传中...',
          mask: true
        })
      }

      wx.uploadFile({
        url: this.baseUrl + (options.url || '/upload/'),
        filePath: options.filePath,
        name: options.name || 'file',
        formData: options.formData || {},
        header: {
          ...this.header,
          ...options.header
        },
        success: (res) => {
          if (options.showProgress !== false) {
            wx.hideLoading()
          }

          try {
            const data = JSON.parse(res.data)
            if (data.success !== false) {
              resolve(data)
            } else {
              reject({
                code: 'UPLOAD_ERROR',
                message: data.message || '上传失败'
              })
            }
          } catch (e) {
            reject({
              code: 'PARSE_ERROR',
              message: '响应解析失败'
            })
          }
        },
        fail: (err) => {
          if (options.showProgress !== false) {
            wx.hideLoading()
          }

          reject({
            code: 'UPLOAD_FAIL',
            message: '上传失败',
            originalError: err
          })
        }
      })
    })
  }
}

// 创建请求实例
const request = new Request()

module.exports = request